<template>
  <div id="login">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
            v-model="userAccount"
            name="userAccount"
            label="账号"
            placeholder="账号"
            :rules="[{ required: true, message: '请输入账号' }]"
        />
        <van-field
            v-model="userPassword"
            type="password"
            name="userPassword"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请输入密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>

  </div>
</template>

<script setup lang="ts">
import {useRouter} from "vue-router";
import {onMounted, ref} from 'vue';
import myAxios from "../../plugins/myAxios.ts";
import {showFailToast} from "vant";
import {getCurrentUser} from "../../services/user.ts";
import type {UserType} from "../../models/user";
import {setCurrentUserState} from "../../states/user.ts";

const router = useRouter()
const userAccount = ref('');
const userPassword = ref('');
const emit = defineEmits(['update:isLogin']);

onMounted(async () => {
  const currentUser: UserType | null = await getCurrentUser()
  // console.log('currentUser', currentUser)
  if (currentUser == null) {
    router.replace('/explore')
  }
})

const onSubmit = async () => {
  const res = await myAxios.post('/user/login', {
    userAccount: userAccount.value,
    userPassword: userPassword.value
  })
  if (res.data) {
    // console.log('update:isLogin: true',res.data)
    setCurrentUserState(res.data)
    emit('update:isLogin', true); // 通知父组件更新数据
    // router.replace('/explore')
  } else {
    showFailToast('登录失败')
  }
};
</script>

<style scoped>

</style>